import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:online_bookstore/constants/app_constants.dart';
import 'package:online_bookstore/providers/book_provider.dart';
import 'package:online_bookstore/widgets/book_card.dart';
import 'package:online_bookstore/widgets/loading_shimmer.dart';
import 'package:online_bookstore/widgets/error_widget.dart';

class SearchScreen extends ConsumerStatefulWidget {
  const SearchScreen({super.key});

  @override
  ConsumerState<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends ConsumerState<SearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _performSearch(String query) {
    setState(() {
      _searchQuery = query;
    });
    
    if (query.isNotEmpty) {
      ref.read(booksProvider.notifier).refreshBooks(search: query);
    }
  }

  @override
  Widget build(BuildContext context) {
    final booksState = ref.watch(booksProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Search Books'),
        backgroundColor: Colors.transparent,
        elevation: 0,
      ),
      body: Column(
        children: [
          // Search Bar
          Padding(
            padding: const EdgeInsets.all(AppConstants.defaultPadding),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: 'Search for books, authors, or categories...',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: _searchQuery.isNotEmpty
                    ? IconButton(
                        icon: const Icon(Icons.clear),
                        onPressed: () {
                          _searchController.clear();
                          _performSearch('');
                        },
                      )
                    : null,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(AppConstants.borderRadius),
                ),
              ),
              onChanged: _performSearch,
              onSubmitted: _performSearch,
            ),
          ),

          // Search Results
          Expanded(
            child: _buildSearchResults(booksState),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchResults(BooksState state) {
    if (_searchQuery.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              'Search for books',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
            ),
            SizedBox(height: 8),
            Text(
              'Enter a book title, author, or category',
              style: TextStyle(
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    if (state.isLoading && state.books.isEmpty) {
      return const LoadingShimmer();
    }

    if (state.error != null && state.books.isEmpty) {
      return CustomErrorWidget(
        message: state.error!,
        onRetry: () => _performSearch(_searchQuery),
      );
    }

    if (state.books.isEmpty) {
      return EmptyStateWidget(
        title: 'No Results Found',
        message: 'No books found for "$_searchQuery"',
        icon: Icons.search_off,
        onAction: () {
          _searchController.clear();
          _performSearch('');
        },
        actionText: 'Clear Search',
      );
    }

    return RefreshIndicator(
      onRefresh: () async => _performSearch(_searchQuery),
      child: GridView.builder(
        padding: const EdgeInsets.all(AppConstants.defaultPadding),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.6,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
        ),
        itemCount: state.books.length,
        itemBuilder: (context, index) {
          final book = state.books[index];
          return BookCard(
            book: book,
            onTap: () {
              // Navigate to book detail
            },
          );
        },
      ),
    );
  }
}
